import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get_state_manager/get_state_manager.dart';

import '../commonTool/fm_color_tool.dart';

FMProgressHudState? _globalHud;

class FMProgressHud extends StatefulWidget {
  final double offsetY;
  final Widget child;

  final Duration? maximumDismissDuration;

  final bool isGlobalHud;

  const FMProgressHud(
      {Key? key,
      required this.child,
      this.offsetY = 0,
      this.isGlobalHud = false,
      this.maximumDismissDuration})
      : super(key: key);

  @override
  State<FMProgressHud> createState() => FMProgressHudState();

  static void showLoading() {
    Future.delayed(const Duration(milliseconds: 50),(){
      _globalHud?.showLoading();
    });
  }

  static void hideLoading() {
    _globalHud?.dismiss();
  }
}

class FMProgressHudState extends State<FMProgressHud> {
  bool _isVisible = false;
  double _opacity = 0.0;
  bool hasBuildAfterShow = false;

  @override
  void initState() {
    if (widget.isGlobalHud) {
      _globalHud = this;
    }
    super.initState();
  }

  /// dismiss hud
  void dismiss() {
    if (mounted) {
      setState(() {
        _opacity = 0;
        if (!hasBuildAfterShow) {
          _isVisible = false;
        }
      });
    }
  }

  void showLoading() {
    if (mounted) {
      _isVisible = true;
      setState(() {
        _opacity = 1;
      });
      hasBuildAfterShow = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    hasBuildAfterShow = true;
    return Directionality(
        textDirection: TextDirection.ltr,
        child: Stack(children: <Widget>[
          widget.child,
          Offstage(
            offstage: !_isVisible,
            child: AnimatedOpacity(
              onEnd: () {
                if (_opacity == 0 && _isVisible) {
                  // hide
                  setState(() {
                    _isVisible = false;
                  });
                }
              },
              opacity: _opacity,
              duration: const Duration(milliseconds: 250),
              child: _createHud(),
            ),
          )
        ]));
  }

  Widget _createHud() {
    return Center(
        child: Container(
          width: 95,
          height: 85,
          margin: EdgeInsets.only(bottom: widget.offsetY),
          decoration: BoxDecoration(
            color: FMColorTool.color('#373C45',alpha: 0.85),
            borderRadius: const BorderRadius.all(Radius.circular(8)),
          ),
          child: Container(
            margin: const EdgeInsets.only(top: 0),
            child: Theme(
              data: ThemeData(
                cupertinoOverrideTheme: const CupertinoThemeData(
                  brightness: Brightness.dark,
                ),
              ),
              child: const CupertinoActivityIndicator(
                radius: 20,
              ),
            ),
          ),
        )
    );
  }
}
